package com.yanyeori.framework.web.advice;

import com.yanyeori.framework.core.constant.BaseWebCodeEnum;
import com.yanyeori.framework.core.exception.ArgumentException;
import com.yanyeori.framework.core.exception.BaseException;
import com.yanyeori.framework.core.model.WebResponse;
import com.yanyeori.framework.web.configprop.WebConfigProps;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Objects;

/**
 * 统一异常处理
 *
 * @author chenkuan 2020/12/17
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionAdvice {

    private final WebConfigProps config;

    public GlobalExceptionAdvice(WebConfigProps config) {
        this.config = config;
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public WebResponse<?> handle(MethodArgumentNotValidException e) {
        String message = Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage();
        log.warn("MethodArgumentNotValidException: {}", message);
        return WebResponse.fail(BaseWebCodeEnum.SERVER_EXCEPTION.code(), message);
    }

    @ExceptionHandler(BindException.class)
    public WebResponse<?> handleBindException(BindException e) {
        log.warn(BaseWebCodeEnum.SERVER_EXCEPTION.msg(), e);
        String message = e.getAllErrors().get(0).getDefaultMessage();
        return WebResponse.fail(BaseWebCodeEnum.SERVER_EXCEPTION.code(), message);
    }

    @ExceptionHandler(ArgumentException.class)
    public WebResponse<?> handle(ArgumentException e) {
        log.warn(BaseWebCodeEnum.SERVER_EXCEPTION.msg(), e);
        return WebResponse.fail(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(BaseException.class)
    public WebResponse<?> handle(BaseException e) {
        log.error(BaseWebCodeEnum.SERVER_EXCEPTION.msg(), e);
        return WebResponse.fail(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public WebResponse<?> handle(Exception e) {
        log.error(BaseWebCodeEnum.SERVER_EXCEPTION.msg(), e);
        String message = e.getMessage();
        int errMsgLength = config.getServerErrMsgLength();
        message = message == null || errMsgLength <= 0 ?
                BaseWebCodeEnum.SERVER_EXCEPTION.msg() : message.substring(0, Math.min(message.length(), errMsgLength));
        return WebResponse.fail(BaseWebCodeEnum.SERVER_EXCEPTION.code(), message);
    }
}
